#!/usr/bin/env python3
"""
TCP协议处理器
"""
import asyncio
import base64
import uuid
from datetime import datetime, timezone

from .base_handler import ProtocolHandler
from .utils import append_jsonl
from .logger import op_logger

class TCPHandler(ProtocolHandler):
    """
    TCP协议处理器，实现简单的TCP回显服务
    """

    def __init__(self, host, port, log_file):
        """
        初始化TCP处理器

        Args:
            host (str): 监听主机地址
            port (int): 监听端口
            log_file (str): 日志文件路径
        """
        super().__init__("tcp", host, port, log_file)

    async def start(self):
        """
        启动TCP服务器
        """
        self._server = await asyncio.start_server(self._handle, host=self.host, port=self.port)
        addrs = ", ".join(str(sock.getsockname()) for sock in self._server.sockets)
        op_logger.info("TCP监听于 %s", addrs)
        return asyncio.create_task(self._server.serve_forever())

    async def _handle(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter):
        """
        处理TCP客户端连接，实现回显功能

        Args:
            reader (asyncio.StreamReader): 用于从连接中读取数据的流读取器
            writer (asyncio.StreamWriter): 用于向连接写入数据的流写入器
        """
        peer = writer.get_extra_info("peername") or ("unknown", 0)
        session_id = str(uuid.uuid4())
        start_ts = datetime.now(timezone.utc)
        raw_buf = bytearray()
        op_logger.info("TCP新连接 %s 会话=%s", peer, session_id)
        try:
            while True:
                data = await reader.read(4096)
                if not data:
                    break
                raw_buf.extend(data)
                writer.write(data)
                await writer.drain()
        except Exception as e:
            op_logger.exception("TCP处理器错误 %s: %s", session_id, e)
        finally:
            entry = {
                "session_id": session_id,
                "start_time": start_ts.isoformat(),
                "end_time": datetime.now(timezone.utc).isoformat(),
                "duration_seconds": (datetime.now(timezone.utc) - start_ts).total_seconds(),
                "remote_ip": peer[0],
                "remote_port": peer[1],
                "raw_base64": base64.b64encode(bytes(raw_buf)).decode("ascii"),
            }
            await self.persist(entry)
            try:
                writer.close()
                await writer.wait_closed()
            except Exception:
                pass
            op_logger.info("TCP关闭会话 %s 来自 %s", session_id, peer)
